package com.example.mobile2030606175lyh0618;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    public void openDB(Context context){
        openHelper=new MySQLiteOpenHelper(context,"student.db",null,1);
        try{
            database=openHelper.getWritableDatabase();
        }catch (Exception e){
            database=openHelper.getWritableDatabase();
        }
    }
public void closeDB(){
        if (database!=null){
            database.close();
            database=null;
        }
        if (openHelper!=null){
            openHelper.close();
            openHelper=null;
        }
     }
     public List<Users>QueryAll(Context context){
        List<Users> usersList=new ArrayList<>();
        openDB(context);
         Cursor cursor = database.query("users",null,null,null,null,null,
                 null);
         if(cursor.moveToFirst()){
             do {
                 int id=cursor.getInt(0);
                 String name=cursor.getString(1);
                 int age= cursor.getInt(2);
                 float score=cursor.getFloat(3);
                 usersList.add(new Users(id,name,age,score));
             }while (cursor.moveToNext());
         }
         cursor.close();
         closeDB();
         return usersList;
     }
     public long insert(Context context,Users user){
        openDB(context);
         ContentValues values = new ContentValues();
         values.put("name", user.getName());
         values.put("age", user.getAge());
         values.put("scor", user.getScore());
         long result = database.insert("users",null,values);
         closeDB();
         return result;
     }
}
